﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.UserData;
using Microsoft.Phone.Tasks;
using AVICFEEDSApp.BingMapsGeocodeService;
using Microsoft.Phone.Shell;
using System.Device.Location;
using AVICFEEDSApp.Properties;
using System.Windows.Input;
using Microsoft.Phone.Controls;

namespace AVICFEEDSApp
{
	public partial class OldMainPage : PhoneApplicationPage
	{
		private GeocodeServiceClient _geocodeServiceClient = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
		private SaveContactTask _saveContactTask = new SaveContactTask();
		private BingMapsTask _bingMapsTask = new BingMapsTask();
		private Contacts _contacts = new Contacts();

		public OldMainPage()
		{
			InitializeComponent();

			this.Loaded += new RoutedEventHandler(OldMainPage_Loaded);
			this._saveContactTask.Completed += new EventHandler<SaveContactResult>(SaveContactTask_Completed);
			this._geocodeServiceClient.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(GeocodeServiceClient_GeocodeCompleted);
			this._contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
		}

		private void OldMainPage_Loaded(object sender, RoutedEventArgs e)
		{
			// See if the navigation to this page was due to a search extension
			if (NavigationContext.QueryString.ContainsKey("PlaceName") == true && NavigationContext.QueryString.ContainsKey("PlaceLatitude") == true && NavigationContext.QueryString.ContainsKey("PlaceLongitude") == true)
			{
				double longitude = 0;
				double latitude = 0;
				if (double.TryParse(NavigationContext.QueryString["PlaceLongitude"], out longitude) == true)
				{
					if (double.TryParse(NavigationContext.QueryString["PlaceLatitude"], out latitude) == true)
					{
						Common.SaveContact(this._saveContactTask, NavigationContext.QueryString["PlaceName"], longitude, latitude);
					}
				}
			}
			else
			{
				LoadContacts();
			}

			PanoramaControl.DefaultItem = PanoramaControl.Items[1];
		}

		/// <summary>
		/// Loads contacts on the device that are saved as POIs.
		/// </summary>
		private void LoadContacts()
		{
			this._contacts.SearchAsync("@[", FilterKind.DisplayName, null);
		}

		protected void GeocodeServiceClient_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
		{
			// Clear the progress indicator
			SystemTray.SetProgressIndicator(this, new ProgressIndicator()
			{
				IsVisible = false
			});

			// Show an error message if something went wrong
			if (e.Error != null)
			{
				MessageBox.Show(e.Error.Message, "Search error", MessageBoxButton.OK);
			}
			else if (e.Result == null || e.Result.Results == null || e.Result.Results.Count == 0)
			{
				MessageBox.Show("We couldn't find any matches for the address you entered.", "No results", MessageBoxButton.OK);
			}
			else
			{
				// Save the result as a contact
				GeocodeResult geocodeResult = e.Result.Results[0];
				Common.SaveContact(this._saveContactTask, geocodeResult.DisplayName, geocodeResult.Locations[0].Longitude, geocodeResult.Locations[0].Latitude, geocodeResult.Address);
			}
		}

		private void SaveContactTask_Completed(object sender, SaveContactResult e)
		{
			// Check if the user tapped the save button
			if (e.TaskResult == TaskResult.OK)
			{
				MessageBox.Show("You may need to refresh contacts via Bluetooth on the Pioneer navigation system.  Press your phone's back button to return to search results.", "Contact saved as POI", MessageBoxButton.OK);
			}

			// Reload the POIs in the contact list
			LoadContacts();
		}

		private void POISearch_GotFocus(object sender, RoutedEventArgs e)
		{
			// Clears or selects text in the POISearch textbox
			if (POISearch.Text.Equals("Enter name...", StringComparison.InvariantCultureIgnoreCase) == true)
			{
				POISearch.Text = "";
			}
			else
			{
				POISearch.SelectAll();
			}
		}

		private void POISearch_LostFocus(object sender, RoutedEventArgs e)
		{
			// Enters watermark text into the POISeach textbox
			if (String.IsNullOrEmpty(POISearch.Text) == true)
			{
				POISearch.Text = "Enter name...";
			}
		}

		private void POISearch_KeyUp(object sender, KeyEventArgs e)
		{
			// Executes the search when the user taps the Enter key
			if (String.IsNullOrEmpty(POISearch.Text) == false && e.Key == Key.Enter)
			{
				_bingMapsTask.SearchTerm = POISearch.Text;
				_bingMapsTask.ZoomLevel = 14;
				_bingMapsTask.Show();
			}
		}

		private void AddressSearch_GotFocus(object sender, RoutedEventArgs e)
		{
			// Clears or selects the text of the AddressSearch textbox
			//if (AddressSearch.Text.Equals("Enter address...", StringComparison.InvariantCultureIgnoreCase) == true)
			//{
			//    AddressSearch.Text = "";
			//}
			//else
			//{
			//    AddressSearch.SelectAll();
			//}
		}

		private void AddressSearch_KeyUp(object sender, KeyEventArgs e)
		{
			// Executes the search when the user taps the Enter key
			//if (String.IsNullOrEmpty(AddressSearch.Text) == false && e.Key == Key.Enter)
			{
				// Start a progress bar animation
				SystemTray.SetProgressIndicator(this, new ProgressIndicator()
				{
					IsIndeterminate = true,
					IsVisible = true,
					Text = "Searching for address..."
				});

				// Create the search request
				GeocodeRequest geocodeRequest = new GeocodeRequest()
				{
					Credentials = new Credentials()
					{
						ApplicationId = Strings.BingMapsCredentials
					},
					//Query = AddressSearch.Text,
					Options = new GeocodeOptions()
					{
						Filters = new List<FilterBase>()
		                {
		                    new ConfidenceFilter()
		                    {
		                        MinimumConfidence = BingMapsGeocodeService.Confidence.High
		                    },
		                }
					}
				};

				// Execute the search
				this._geocodeServiceClient.GeocodeAsync(geocodeRequest);
			}
		}

		private void AddressSearch_LostFocus(object sender, RoutedEventArgs e)
		{
			// Enters watermark text into the AddressSearch textbox
			//if (String.IsNullOrEmpty(AddressSearch.Text) == true)
			//{
			//    AddressSearch.Text = "Enter address...";
			//}
		}

		private void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
		{
			// Fills the Contact list after the search completes
			try
			{
				// Filter contacts that contain a @[
				ContactResultsData.DataContext =
					from Contact contact in e.Results
					select new KeyValuePair<string, string>(contact.DisplayName.Substring(0, contact.DisplayName.IndexOf("@[")), contact.DisplayName);
			}
			catch (System.Exception)
			{
				//No results
			}

			if (ContactResultsData.Items.Count > 0)
			{
				ContactResultsLabel.Visibility = System.Windows.Visibility.Collapsed;
			}
			else
			{
				ContactResultsLabel.Text = "no saved POIs";
			}
		}

		private void ContactResults_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			// Shows the POI on the map when tapped
			TextBlock textBlock = sender as TextBlock;
			if (textBlock != null)
			{
				GeoCoordinate geoCoordinate = AVICDecoderRing.Decode(textBlock.Tag.ToString());
				if (geoCoordinate != GeoCoordinate.Unknown)
				{
					this._bingMapsTask.Center = geoCoordinate;
					this._bingMapsTask.ZoomLevel = 16;
					this._bingMapsTask.SearchTerm = textBlock.Text;

					this._bingMapsTask.Show();
				}
			}
		}

		private void AddressSearchButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
		}
	}
}